﻿using Dapper_Core.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;

namespace Dapper_Core.DAL.Impl
{
    public class TransactionContext : DisposableObject
    {
        public IDbConnection Connection { get; set; }
        public IDbTransaction Transaction { get; private set; }
        private bool _committed = true;
        private bool Committed
        {
            set { _committed = value; }
            get { return _committed; }
        }

        public TransactionContext()
        {
            Connection = ConnectionFactory.GetOpenConnection();
        }

        public TransactionContext(DBEntity dbEntity)
        {
            Connection = ConnectionFactory.GetOpenConnection(dbEntity);
        }

        public void BeginTransaction()
        {
            if (this.Connection.State != ConnectionState.Open)
                this.Connection.Open();
            this.Transaction = this.Connection.BeginTransaction();
            this.Committed = false;
        }

        public void Commit()
        {
            if (Committed) return;
            this.Transaction.Commit();
            this._committed = true;
            if (this.Connection != null && this.Connection.State == ConnectionState.Open)
            {
                this.Connection.Close();
            }
            if (this.Transaction != null)
            {
                this.Transaction.Dispose();
                this.Transaction = null;
            }
        }

        public void Rollback()
        {
            if (Committed) return;
            this.Transaction.Rollback();
            this._committed = true;
            if (this.Connection != null && this.Connection.State == ConnectionState.Open)
            {
                this.Connection.Close();
            }
            if (this.Transaction != null)
            {
                this.Transaction.Dispose();
                this.Transaction = null;
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }
            if (this.Connection != null && this.Connection.State == ConnectionState.Open)
            {
                this.Connection.Close();
            }
            if (this.Transaction != null)
            {
                this.Transaction.Dispose();
                this.Transaction = null;
            }
        }
    }
}